package top.qingyunge.autumn.config.DruidConfig;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Configuration
public class DateSourceConfig {
    @Autowired
    public DataSourcePropertiesMapWrapper dataSourcePropertiesMapWrapper;

    @Qualifier("targetDataSources")
    public Map<Object, Object> targetDataSources() {
        Map<Object, Object> configSources = new HashMap<>();
        for (String key : dataSourcePropertiesMapWrapper.dataSourcesMap.keySet()) {
            DataSourcePropertiesMapWrapper.DataSourceProperties oneDataSourceProperties = dataSourcePropertiesMapWrapper.dataSourcesMap.get(key);

            DataSource configSource = DataSourceBuilder.create()
                    .type(DruidDataSource.class)
                    .driverClassName(oneDataSourceProperties.getDriverClassName())
                    .url(oneDataSourceProperties.getUrl())
                    .username(oneDataSourceProperties.getUsername())
                    .password(oneDataSourceProperties.getPassword())
                    .build();

            configSources.put(key, configSource);
        }
        return configSources;
    }

    @Bean
    public DataSourceRouter dataSource() {
        DataSourceRouter routingDataSource = new DataSourceRouter();
        routingDataSource.setTargetDataSources(targetDataSources());
        routingDataSource.setDefaultTargetDataSource(targetDataSources().get("blog")); // 默认数据源
        log.info("初始化数据源: {}",targetDataSources().toString());
        return routingDataSource;
    }
    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}
